.TH std::bitset::count 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::bitset::count \- std::bitset::count

.SH Synopsis
   std::size_t count() const;  (noexcept since C++11)
                               (constexpr since C++23)

   Returns the number of bits that are set to true.

.SH Parameters

   \fI(none)\fP

.SH Return value

   Number of bits that are set to true.

.SH Example


// Run this code

 #include <bitset>
 #include <iostream>

 int main()
 {
     std::bitset<8> b("00010010");
     std::cout << "Initial value: " << b << '\\n';

     // Find the first unset bit
     std::size_t idx = 0;
     while (idx < b.size() && b.test(idx))
         ++idx;

     // Continue setting bits until half the bitset is filled
     while (idx < b.size() && b.count() < b.size() / 2)
     {
         b.set(idx);
         std::cout << "Setting bit " << idx << ": " << b << '\\n';
         while (idx < b.size() && b.test(idx))
             ++idx;
     }

 }

.SH Output:

 Initial value: 00010010
 Setting bit 0: 00010011
 Setting bit 2: 00010111

.SH See also

   size     returns the number of bits that the bitset holds
            \fI(public member function)\fP
   popcount counts the number of 1 bits in an unsigned integer
   (C++20)  \fI(function template)\fP
